package main

import (
	"encoding/json"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

type Person struct {
	Id        int64
	Name      string
	Addresses []*Address `gorm:"many2many:person_addresses;"`
}

type Address struct {
	ID   uint
	Name string
}

type PersonAddress struct {
	PersonID  int64 `gorm:"primaryKey"`
	AddressID uint  `gorm:"primaryKey"`
	CreatedAt time.Time
	DeletedAt gorm.DeletedAt
}

func main() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	// 1. 定义数据库的地址
	// charset 字符编码类型
	// parseTime 时间格式
	// loc 时间分区
	dsn := "root:jxkj@123@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	fmt.Println(db)

	// 2. 自动创建表
	//db.AutoMigrate(&Person{}, &Address{}, &PersonAddress{})

	//// 3. 新增数据
	person := &Person{
		Name: "MiracleWong",
		Addresses: []*Address{
			{Name: "Home"}, {Name: "Company"},
		},
	}
	db.Create(person)

	persons := []*Person{}
	db.Preload("Addresses").Find(&persons)
	personBytes, _ := json.Marshal(persons)
	fmt.Println(string(personBytes))
}
